﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using Cofe.Core;
using Cofe.Core.Implements;
using Cofe.Core.Interfaces;
using Cofe.Core.Security;
using Cofe.Web;
using Cofe.Web.Utils;

namespace Cofe.Web.Models
{  
    public class VolumeInfoViewModel 
    {
        public VolumeInfo VolumeInfo { get; set; }
        public VolumePermission AdminPermission { get { return VolumePermission.ReadWrite; } }
        public VolumePermission MePermission { get; set; }
        public VolumePermission FamilyMemberPermission { get; set; }
        public VolumePermission FriendPermission { get; set; }
        public VolumePermission PublicPermission { get; set; }

        public VolumeInfoViewModel()
        {
            VolumeInfo = new VolumeInfo();
            MePermission = VolumePermission.ReadWrite;
            FamilyMemberPermission = VolumePermission.ReadWrite;
            FriendPermission = VolumePermission.Read;
            PublicPermission = VolumePermission.None;
        }

        public static VolumeInfoViewModel FromVolumeInfo(IVolumeInfo volumeInfo)
        {
            return FromVolumeInfo((VolumeInfo)volumeInfo);
        }

        public static VolumeInfoViewModel FromVolumeInfo(VolumeInfo volumeInfo)
        {
            VolumeInfoViewModel retVal = new VolumeInfoViewModel();
            retVal.VolumeInfo = volumeInfo;
            var policies = CofeServices.SecurityManager.GetPermissionPolicies(pm => pm is VolumePermissionPolicy &&
                (pm as VolumePermissionPolicy).VolumeId == volumeInfo.VolumeId).Select(pm => pm as VolumePermissionPolicy);
            Func<WebUserRole, PermissionType> getPermission = (role) =>
                {
                    PermissionType rv = PermissionType.None;
                    foreach (var p in policies)
                        if (p.RequiredRole.Contains(role.GetRoleString()) || p.RequiredRole.Length == 0)
                            rv |= p.GrantedPermission;
                    return rv;
                };

            retVal.MePermission = getPermission(WebUserRole.Me).ToVolumePermission();
            retVal.FamilyMemberPermission = getPermission(WebUserRole.FamilyMember).ToVolumePermission();
            retVal.FriendPermission = getPermission(WebUserRole.Friend).ToVolumePermission();
            retVal.PublicPermission = getPermission(WebUserRole.Other).ToVolumePermission();
            return retVal;
        }
    }
}